import axios from "axios";
import { ExtraRpcs, ChainIds } from "../config/chain-config.js";

function removeEndingSlashObject(rpc) {
  if (typeof rpc === "string") {
    return {
      url: removeEndingSlash(rpc),
    };
  } else {
    return {
      ...rpc,
      url: removeEndingSlash(rpc.url),
    };
  }
}

function removeEndingSlash(rpc) {
  return rpc.endsWith("/") ? rpc.substr(0, rpc.length - 1) : rpc;
}

export function populateChain(chain, chainTvls) {
  const extraRpcs = ExtraRpcs[chain.chainId]?.rpcs;

  if (extraRpcs !== undefined) {
    const rpcs = extraRpcs.map(removeEndingSlashObject);

    chain.rpc
      .filter((rpc) => !rpc.includes("${INFURA_API_KEY}"))
      .forEach((rpc) => {
        const rpcObj = removeEndingSlashObject(rpc);
        if (rpcs.find((r) => r.url === rpcObj.url) === undefined) {
          rpcs.push(rpcObj);
        }
      });

    chain.rpc = rpcs;
  } else {
    chain.rpc = chain.rpc.map(removeEndingSlashObject);
  }

  const chainSlug = ChainIds[chain.chainId];

  if (chainSlug !== undefined) {
    const defiChain = chainTvls.find((c) => c.name.toLowerCase() === chainSlug);

    return defiChain === undefined
      ? chain
      : {
          ...chain,
          tvl: defiChain.tvl,
          chainSlug,
        };
  }
  return chain;
}

export async function generateChainData() {
  const chains = await axios.get("https://chainid.network/chains.json");
  const chainTvls = await axios.get("https://api.llama.fi/chains");
  const sortedChains = chains.data
    .filter((c) => c.name !== "420coin") // same chainId as ronin
    .map((chain) => populateChain(chain, chainTvls.data))
    .sort((a, b) => {
      return (b.tvl ?? 0) - (a.tvl ?? 0);
    });
  return sortedChains;
}
